<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card ref="el">
      <!-- 导出表格按钮 -->
      <el-row style="margin-bottom: 15px">
        <el-col>
          <el-button type="primary" @click="exportExcel">导出表格</el-button>
        </el-col>
        <el-col>
          <el-button type="primary" @click="exportExcel2"
            >导出选中表格</el-button
          >
        </el-col>
        <!-- 
        在网上找了一个打印组件vue-print-nb
        使用方式
        安装 npm install vue-print-nb --save
        在main.js文件中注册
        import Print from 'vue-print-nb'
        Vue.use(Print);
        页面中使用按钮添加v-print,给需要打印的容器加一个id,打印按钮传入这个id
        -->
        <el-col>
          <el-button v-print="'#exportTab'" type="warning">打印</el-button>
        </el-col>
        <el-col>
          <el-button @click="filterSelected" type="success"
            >筛选已选志愿学生</el-button
          >
        </el-col>
        <el-col>
          <el-button type="warning" @click="filterNotSelected"
            >筛选未选志愿学生</el-button
          >
        </el-col>
        <el-col>
          <el-button type="danger" @click="resetfilter">重置筛选</el-button>
        </el-col>
      </el-row>

      <!-- 表格一，用于导出所有。渲染学生列表 -->
      <el-table
        :data="studentList"
        border
        stripe
        id="exportTab"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'selectTime', order: 'ascending' }"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          label="学生id"
          prop="_id"
          width="220"
        ></el-table-column>
        <el-table-column
          label="学生姓名"
          prop="username"
          width="100"
        ></el-table-column>
        <el-table-column
          label="学生邮箱"
          prop="email"
          width="150"
        ></el-table-column>
        <el-table-column
          label="学生志愿"
          prop="title1"
          :filters="articleList"
          :filter-method="filterHandlerStu"
          width="180"
        >
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.title1.title !== '未选择'">{{
              scope.row.title1.title
            }}</el-tag>
            <el-tag type="danger" v-else>未选择</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="指导老师"
          prop="title1"
          :filters="teacherList"
          :filter-method="filterHandlerTec"
          width="140"
        >
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.title1.title !== '未选择'">{{
              scope.row.title1.Tauthor.username
            }}</el-tag>
            <el-tag type="danger" v-else>未选择</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="选题时间（优先级）" sortable prop="selectTime">
          <template slot-scope="scope">{{
            scope.row.selectTime | dateFormat
          }}</template>
        </el-table-column>
        <el-table-column type="expand" label="设计要求" width="200">
          <template slot-scope="scope">
            <div class="design_detail">
              <el-input
                type="textarea"
                :rows="5"
                readonly
                :value="scope.row.title1.content"
              >
              </el-input>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格二， 用于导出选中的项 -->
      <el-table
        :data="multipleSelection"
        border
        stripe
        id="exportTab2"
        style="display: none"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="学生id" prop="_id"></el-table-column>
        <el-table-column label="学生姓名" prop="username"></el-table-column>
        <el-table-column label="学生邮箱" prop="email"></el-table-column>
        <el-table-column label="学生志愿" prop="title1">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">{{ scope.row.title1.title }}</template>
        </el-table-column>
        <el-table-column label="指导老师" prop="title1">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">{{
            scope.row.title1.Tauthor.username
          }}</template>
        </el-table-column>
        <el-table-column label="选题时间（优先级）" sortable prop="selectTime">
          <template slot-scope="scope">{{
            scope.row.selectTime | dateFormat
          }}</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
// 引入导出表格相关依赖
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

export default {
  data() {
    return {
      // 查询参数对象
      queryInfo: {
        query: 'student',
        pagenum: null,
        pagesize: null
      },
      // 学生列表
      studentList: [],
      // 表格二的数据
      multipleSelection: []
    }
  },
  created() {
    // 获取学生列表数据
    this.getStudentList()
  },
  methods: {
    // 获取学生列表
    async getStudentList() {
      // 发送请求获取学生数据
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })

      // 重构数组（将title1属性为空对象，改为不空）
      let result = res.records.map(item => {
        if (item.title1) {
          return item
        } else {
          item.title1 = {
            title: '未选择',
            Tauthor: {
              username: '未选择'
            }
          }
          return item
        }
      })

      this.studentList = res.records

      console.log(result)
      console.log(this.studentList)
    },

    // 表格复选框选中事件
    handleSelectionChange(val) {
      // 将对应行的数据赋值到multipleSelection数组中
      // multipleSelection数组中的数据用于渲染一个隐藏的表格,用于导出选中的表格项
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },

    // 筛选已选志愿学生
    filterSelected() {
      this.queryInfo.query = 'selected'
      this.getStudentList()
    },
    // 筛选未选志愿学生
    filterNotSelected() {
      this.queryInfo.query = 'notselect'
      this.getStudentList()
    },
    // 重置筛选
    resetfilter() {
      this.queryInfo.query = 'student'
      this.getStudentList()
    },

    // 打印
    printf() {
      window.print()
    },

    // 导出表格
    exportExcel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector('#exportTab'),
        xlsxParam
      )

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          '学生志愿终表.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    },

    // 导出表格二
    exportExcel2() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector('#exportTab2'),
        xlsxParam
      )

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          '审核情况表.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    },
    // 学生志愿筛选
    filterHandlerStu(value, row) {
      console.log(row)
      // 筛选出相应题目的
      return row.title1.title === value
    },
    // 指导老师筛选
    filterHandlerTec(value, row) {
      return row.title1.Tauthor.username === value
    }
  },
  computed: {
    // 学生志愿筛选
    articleList() {
      // 重构数组成 [{ text: '', value: '' }] 形式
      var newList = this.studentList.map(v => {
        return {
          text: v.title1.title,
          value: v.title1.title
        }
      })
      // 数组去重
      var result = []
      var obj = {}
      for (var i = 0; i < newList.length; i++) {
        if (!obj[newList[i].text]) {
          result.push(newList[i])
          obj[newList[i].text] = true
        }
      }
      return result
    },
    // 指导老师筛选
    teacherList() {
      // 重构数组成 [{ text: '', value: '' }] 形式
      var newList = this.studentList.map(v => {
        return {
          text: v.title1.Tauthor.username,
          value: v.title1.Tauthor.username
        }
      })
      // 数组去重
      var result = []
      var obj = {}
      for (var i = 0; i < newList.length; i++) {
        if (!obj[newList[i].text]) {
          result.push(newList[i])
          obj[newList[i].text] = true
        }
      }
      return result
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  display: flex;
  justify-content: flex-start;
  .el-col {
    width: auto;
    .el-button {
      margin-right: 15px;
    }
  }
}
.design_detail {
  width: 50%;
}
</style>
